import { signal } from "@preact/signals";
import { moveItem, getIndex } from "./utilities";
import { toast } from "./signals";

const key = "lemon_daisy_presets";
const stor = globalThis.localStorage;

const defaultPresets = ["http://", "https://", "www.", ".", ".com", ".cn", "@"];

export const presets = signal(structuredClone(defaultPresets));

export function initPresets() {
  if (stor[key]?.startsWith("[")) {
    const data = JSON.parse(stor[key]);
    presets.value = data;
  }
  stor[key] = JSON.stringify(presets.value);
}

function store(data) {
  stor[key] = JSON.stringify(data);
  presets.value = data;
}

export function editPreset(word) {
  const input = prompt("填写新内容", word);
  const current = structuredClone(presets.value);
  const index = getIndex(current, word);
  if (input) {
    current[index] = input;
    store(current);
  } else toast("内容不能为空");
}

export function delPreset(word) {
  const current = structuredClone(presets.value);
  if (current.length > 1) {
    const index = getIndex(current, word);
    current.splice(index, 1);
    store(current);
  } else {
    toast("禁止删除");
  }
}

export function movePreset(word, up) {
  const current = structuredClone(presets.value);
  const changed = moveItem(current, word, up);
  store(changed);
}

export function addPreset() {
  const input = prompt("填写新内容");
  const current = structuredClone(presets.value);
  const index = getIndex(current, input);
  if (input && index === -1) {
    current.unshift(input);
    store(current);
  } else {
    toast("内容为空或重复");
  }
}

export function clearPresets() {
  delete stor[key];
}

export function importPresets(data, merge) {
  let result = data;
  const current = structuredClone(presets.value);
  if (merge) {
    result = [...new Set([...current, ...data])];
  }
  store(result);
}

export function resetPresets() {
  importPresets(defaultPresets, false);
}
